import axios from "axios";
import Vue from "vue";
import apiConfig from "@/api/index";
import { MOCK } from "@/api/test";
const { api, config } = apiConfig;
import { res, req } from "./intercepteptors.js";
import qs from "qs";
import {getToken} from '@/utils/auth.js'

/**
 *
 * @param {String} url
 * @param {Object} data
 * @param {?Function} callback
 */
export const ajax = async (url, data, callback) => {
  //axios.defaults.headers['versionno'] = '1.1.2';
  axios.defaults.headers.channelUid = Vue.prototype.$channel
  axios.defaults.headers.versionNo = Vue.prototype.$v
  if (getToken()) {
    axios.defaults.headers.token = getToken();
	//axios.defaults.headers.channelUid = 'xx';  //渠道号
  }
  try {
    let configRequest = {
      url: api[url][0],
      method: api[url][1],
      // 非必传
      ["Content-Type"]: api[url][2]
    };
    let requestData = {
      method: configRequest.method
    };
    if (configRequest.method.toUpperCase() == "POST") {
      requestData.data = data;
    }
    if (configRequest.method.toUpperCase() == "GET") {
      requestData.params = data;
    }
    // JSON Content-Type
    if (configRequest["Content-Type"] === "JSON") {
      requestData.headers = {
        "Content-Type": "application/json;charset=UTF-8"
      };
    }
    // 默认值
    if (configRequest["Content-Type"] === void 0) {
      requestData.headers = {
        "Content-Type": config["Content-Type"]
      };
      requestData.data = qs.stringify(requestData.data);
    }
    if (config.mock) {
      return MOCK[configRequest.url];
    }
    const response = await axios({
      url: configRequest.url,
      ...requestData
    });
    return callback ? callback(response.data) : response.data;
  } catch (error) {
    console.log(error);
  }
};

axios.defaults.timeout = config.timeout;
axios.defaults.baseURL = config.baseURL;

// axios.interceptors.request.use(config => {
//   config = req(config)
//   var token = getToken()
//   axios.defaults.headers.common['versionNo'] = '1.1.3'
//   return config;
// }, error => {
//   return Promise.reject(error)
// })

axios.interceptors.response.use(
  response => {
    response = res(response);
    return response;
  },
  error => {
    console.log("error", error);
    return Promise.reject(error);
  }
);
